package com.xjk.encryp;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

/**
 * @author 许嘉凯
 */
public class HMACUtil {

  public static String calculateHMACSHA256(String data, String key) throws NoSuchAlgorithmException, InvalidKeyException {
    // 指定HMAC-SHA256算法
    String algorithm = "HmacSHA256";
    // 初始化Mac对象
    return calculate(data, key, algorithm);
  }

  public static String calculateHMACMD5(String data, String key) throws NoSuchAlgorithmException, InvalidKeyException {
    // 指定HMAC-SHA256算法
    String algorithm = "HmacMD5";
    return calculate(data, key, algorithm);
  }

  private static String calculate(String data, String key, String algorithm) throws NoSuchAlgorithmException, InvalidKeyException {
    // 初始化Mac对象
    Mac mac = Mac.getInstance(algorithm);
    // 使用给定的密钥初始化Mac对象
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), algorithm);
    mac.init(secretKeySpec);

    // 完成MAC操作
    byte[] hmacBytes = mac.doFinal(data.getBytes());

    // 将结果转换为十六进制字符串
    StringBuilder sb = new StringBuilder();
    for (byte b : hmacBytes) {
      sb.append(String.format("%02x", b));
    }

    return sb.toString();
  }

  public static void main(String[] args) {
    try {
      // 原始消息
      String message = "This is a confidential message";
      // 密钥（在实际应用中，密钥应保密且随机生成）
      String secret = "secretKey";

      // 使用HMAC-SHA256算法计算HMAC
      String hmacSha256 = calculateHMACSHA256(message, secret);

      System.out.println("HMAC-SHA256: " + hmacSha256);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
